package com.wang.moduler.app

import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.wang.moduler.R
import com.wang.moduler.model.Repos
import com.wang.moduler.model.ReposViewModel
import com.wang.moduler.service.GithubApi
import com.wkh.common.app.BaseActivity
import com.wkh.common.http.HttpHelper
import kotlinx.android.synthetic.main.activity_test.view.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class TestActivity : BaseActivity(R.layout.activity_test, true) {

    private val tag = "TestActivity"

    private var reposViewModel: ReposViewModel? = null

    override fun initView() {

        reposViewModel = ViewModelProvider(this).get(ReposViewModel::class.java)
        reposViewModel?.reposModel?.run {
            observe(this@TestActivity,
                Observer<Repos> { it ->
                    if (it != null) {
                        rootView.userInfo.text = "${it?.name}"
                    }
                })
        }


        rootView.testButton.setOnClickListener {
            launch {

                var result = HttpHelper.get().getRetrofit().getService(GithubApi::class.java)
                    .getReposWithCoroutine()

                reposViewModel?.run {
                    updateData(result)
                }
            }
        }
    }

    override fun onReuseInit() {
        rootView.userInfo.text = "初始字样"
    }


    private suspend fun method1() {
        delay(1000L)
        Log.i(tag, "method1")
        reposViewModel?.run {
            var temp = Repos(1, "Result -> 挂起方法1休眠1s完成")
            updateData(temp)
        }
    }

    private suspend fun method2() {
        delay(4000L)
        Log.i(tag, "method2")
        reposViewModel?.run {
            var temp = Repos(2, "Result -> 挂起方法2休眠4s完成")
            updateData(temp)
        }
    }

    private suspend fun method3() {
        delay(3000L)
        Log.i(tag, "method3")
        reposViewModel?.run {
            var temp = Repos(3, "Result -> 挂起方法3休眠3s完成")
            updateData(temp)
        }
    }

}